<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" size="mini" @click="addCategoriesDialog" @close="emtyList">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table :data="categoriesList" :columns="columns" show-index border stripe show-row-hover :selection-type="false" :expand-type="false" class="tree-table">
        <!-- 自定义是否有效列模板 -->
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-error" style="color: red" v-if="scope.row.cat_deleted"></i>
          <i class="el-icon-success" style="color: greenyellow" v-else></i>
        </template>
        <!-- 自定义排序列模板 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 自定义操作列模板 -->
        <template slot="caozuo" slot-scope="scope">
          <el-button size="mini" type="primary" class="el-icon-edit" @click="showEidtDialog(scope.row.cat_id)">编辑</el-button>
          <el-button size="mini" type="danger" class="el-icon-delete" @click="removeCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="addDialogIsShow" width="50%">
      <el-form :model="addCateGoriesForm" :rules="addCateGoriesrules" ref="addCateGoriesRef" label-width="80px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateGoriesForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="分类父级" prop="cat_pid">
          <el-cascader v-model="selectedKeys" :options="addFormList" :props="cascaderProps" @change="handleChange" clearable></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogIsShow = false">取 消</el-button>
        <el-button type="primary" @click="addCategories">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editDialogIsShow" width="50%">
      <el-form :model="editCateGoriesForm" :rules="editCateGoriesrules" ref="editCateGoriesRef" label-width="80px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateGoriesForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogIsShow = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'categories',
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类数据
      categoriesList: [],
      //商品分类总数
      totalNum: 0,
      //tree-table每一列的配置项
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        //自定义列
        { label: '是否有效', type: 'template', template: 'isOk' },
        { label: '排序', type: 'template', template: 'order' },
        { label: '操作', type: 'template', template: 'caozuo' },
      ],
      //控制对话框显隐
      addDialogIsShow: false,
      addCateGoriesForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
      },
      addFormList: [],
      //级联选择器的配置项
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true, //可以选择任意一项不需要关联父级
      },
      //当前用户选择的级联值
      selectedKeys: [],
      //添加分类表单校验规则
      addCateGoriesrules: {
        cat_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
      },
      //编辑对话框显隐
      editDialogIsShow:false,
      editCateGoriesForm:{},
      editCateGoriesrules:{
          cat_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
      }
    }
  },
  created() {
    this.getCateGoriesList()
  },
  methods: {
    async getCateGoriesList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('请求分类数据失败！')
      }
      this.categoriesList = res.data.result
      this.totalNum = res.data.total
      //   console.log(this.categoriesList, this.totalNum)
    },
    //密码大小发生改变时
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getCateGoriesList()
    },
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getCateGoriesList()
    },
    //添加分类触发
    async addCategoriesDialog() {
      this.addDialogIsShow = true
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分类数据请求失败！')
      }
      this.addFormList = res.data
    },
    //添加商品分类
    addCategories() {
      this.$refs.addCateGoriesRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.err('确保输入是否正确！')
        }
        const {data:res} = await this.$http.post('categories',this.addCateGoriesForm)
        if(res.meta.status !==201){
            return this.$message.error('添加分类失败！')
        }
        this.getCateGoriesList()
        this.addDialogIsShow = false
        return this.$message.success('添加分类成功！')
      })
    },

    //监听级联选择器改变
    handleChange() {
      if (this.selectedKeys.length > 0) {
        this.addCateGoriesForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addCateGoriesForm.cat_level = this.selectedKeys.length
      }else{
          this.addCateGoriesForm.cat_pid = 0
          this.addCateGoriesForm.cat_level = 0
      }
    },
    emtyList(){
        //resetFields elementui提供的表单重置 方法
        this.$refs.addCateGoriesRef.resetFields()
        this.selectedKeys = []
        this.addCateGoriesForm.cat_pid = 0
        this.addCateGoriesForm.cat_level = 0
    },
    //删除商品分类
    removeCate(id){
        this.$confirm('确定要删除该商品分类吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res} = await this.$http.delete(`categories/${id}`)
          if(res.meta.status !==200){
              return this.$message.error('商品分类删除失败！')
          }
          this.getCateGoriesList()
          this.$message.success('已删除分类')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    async showEidtDialog(id){
        this.editDialogIsShow = true
        const {data:res} = await this.$http.get(`categories/${id}`)
        if(res.meta.status !==200){
            return this.$message.error('编辑失败！')
        }
        this.editCateGoriesForm = res.data
    },
    editCate(){
        this.$refs.editCateGoriesRef.validate(async valid =>{
            if(!valid){
                return this.$message.error('确保输入是否正确！')
            }
            
            const {data:res} = await this.$http.put(`categories/${this.editCateGoriesForm.cat_id}`,{
                cat_name: this.editCateGoriesForm.cat_name
            })
            if(res.meta.status !==200){
                return this.$message.error('编辑失败！')
            }
            this.editDialogIsShow = false
            this.getCateGoriesList()
            this.$message.success('修改分类成功！')
        })
    }
  },
}
</script>

<style lang="less" scoped>
.tree-table {
  margin-top: 15px;
}
</style>